<?php if (!defined('BASEPATH'))exit('No direct script access allowed');
/**
 * 模块控制器
 */
class Ajax extends MY_Controller {

    function __construct() {
        parent::__construct();
    }
    
    function check_login(){
        if($this->userinfo){
            $mess['reqStatus'] = true;
        }else{
            $mess['reqStatus'] = false;
        }
        echo JSON($mess);exit;
    }
    
    function ajax_user_code(){
        if($_POST){
            $shop_id = isset($_POST['shopId']) ? trim($_POST['shopId']) : 0;
            $shop_id = decrypt_lottery_id($shop_id);
            $shop = $this->db->query("select q_uid,qishu,q_user_code,q_showtime from tan_go_shoplist where id = $shop_id")->row_array();
            $records = $this->db->query("select goucode from tan_go_member_go_record where shopid = $shop_id and shopqishu = $shop[qishu] and uid = ".$this->userinfo['user_id']." order by id desc")->result_array();
            $html = "";
            $count = 0;
            foreach ($records as $key=>$val){
                $code_arr = explode(",", $val['goucode']);
                foreach ($code_arr as $code){
                    $count ++;
                    if($code == $shop['q_user_code'] && $shop['q_showtime'] == "N"){
                        $html .= "<p class='error'>$code</p>";
                    }else{
                        $html .= "<p>$code</p>";
                    }
                }
            }
            $result = array(
                "reqStatus" => true,
                "codeStr" => $html,
                "codeNum" => $count,
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
    }
    //显示用户每日加息列表信息
    function fetch_day_interests(){
        if($_POST){
            $task_id = isset($_POST['taskId']) ? trim($_POST['taskId']) : 0;
            if(!$task_id){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "";
                echo JSON($mess);exit;
            }
            $task_id = decrypt_interests_id($task_id);
            
            $task = $this->db->query("select invest_id,total_interest_finance,interest_fixed,interest_extra,invest_time,expire_time,status,title,amount from tan_plat_invest_task where id = $task_id order by id desc limit 1")->row_array();
            if(!$task){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "";
                echo JSON($mess);exit;
            }
            $list = $this->db->query("select total_finance total,fixed_finance fixed,extra_finance extra,create_time date_s from tan_plat_interest_detail where invest_id = $task[invest_id] order by id desc ")->result_array();
            foreach ($list as $key=>$val){
                $list[$key]['total'] = number_format($val['total']);
                $list[$key]['fixed'] = number_format($val['fixed']);
                $list[$key]['extra'] = number_format($val['extra']);
                $list[$key]['date_s'] = date("Y-m-d",$val['date_s']);
            }
            $mess = array(
                "reqStatus" => true,
                "info" => array(
                    "fixed" => number_format($task['interest_fixed']),
                    "extra" => number_format($task['interest_extra']),
                    "total" => number_format($task['total_interest_finance']),
                ),
                "list" => $list
            );
            echo JSON($mess);exit;
        }
    }
    function fetch_user_income(){
        if($_POST){
            $type = isset($_POST['timeT']) ? trim($_POST['timeT']) : "m";
            $current_time = time();
            $where = "f.reward_type = 'exper_award'";
            if($type == "m"){//月
                $where .= " and f.create_time > ".($current_time - 30*3600*24);
            }elseif($type == "w"){//周
                $where .= " and f.create_time > ".($current_time - 7*3600*24);
            }else{//日
                $where .= " and f.create_time > ".($current_time - 1*3600*24);
            }
            $list = $this->db->query("select f.user_id,SUM(f.finance) amount,i.nickname,i.head_img from tan_finance_list f left join tan_users_info i on i.user_id = f.user_id where $where group by f.user_id order by amount desc limit 5")->result_array();
            $html = "";
            foreach ($list as $key=>$val){
                if($key == 0){
                    $no = "no1";
                }elseif($key == 1){
                    $no = "no2";
                }elseif($key == 2){
                    $no = "no3";
                }else{
                    $no = "";
                }
                $is_love = $this->userinfo ? (($this->db->query("select * from tan_bbs_fans where is_del = 1 and user_id = $val[user_id] and  followuid = ".$this->userinfo['user_id']." order by id desc")->num_rows()) ? 1 : 0) : 0;
                $html .= "<li>
                                <span class='list-span $no'>No.".($key+1)."</span>
                                <a class='head' href='".www_base_url("u/".encrypt_user_id($val['user_id']))."' target='_blank'><img src='$val[head_img]'/></a>
                                <span class='hername'>
                                        <a href='".www_base_url("u/".encrypt_user_id($val['user_id']))."' target='_blank'>$val[nickname]</a>
                                        <p>".  number_format($val['amount'])."溜溜币</p>
                                </span>
                                <a class='care' href='javascript:void(0);' data-uuid='".encrypt_user_id($val['user_id'])."' data-val='$is_love'>关注<b class='icon ".($is_love ? "icon-loved" : "icon-unlove")."'></b></a>
                        </li>";
            }
            $result = array(
                "reqStatus" => true,
                "htmlData" => $html
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
    }
    
    //关注作者
    function cancel_fan_act(){
        if($_POST){
            $this->is_login();
            $author_id = isset($_POST['author_id']) ? trim($_POST['author_id']) : 0;
            $author_id = decrypt_user_id($author_id);
            $is_fan = isset($_POST['is_fan']) ? trim($_POST['is_fan']) : 0;
            if($author_id == $this->userinfo['user_id']){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "不能关注自己哦";
                echo JSON($mess);exit;
            }
            if($is_fan){//添加
                $status = $this->db->select("f.*")->from("bbs_fans f")->where(array("f.followuid"=>$this->userinfo['user_id'],"f.user_id"=>$author_id,"f.is_del"=>0))->order_by("f.create_time desc")->get()->row_array();
                if($status){
                    $this->db->trans_begin();
                    $query1 = $this->db->query("update tan_bbs_fans set is_del = 1 where followuid = ".$this->userinfo['user_id']." and user_id = ".$author_id);
                    $query2 = $this->db->query("update tan_bbs_count set fans_count = fans_count + 1 where user_id = ".$author_id);
                    $query3 = $this->db->query("update tan_bbs_count set following_count = following_count + 1 where user_id = ".$this->userinfo['user_id']);

                    if($query1 && $query2 && $query3){
                        $this->db->trans_commit();
                        $mess['reqStatus'] = true;
                        echo JSON($mess);exit;
                    }else{
                        $this->db->trans_rollback();
                        $mess['reqStatus'] = false;
                        $mess['errorMsg'] = "操作失败，请稍后重试";
                        echo JSON($mess);exit;
                    }
                }else{
                    $data = array();
                    $data['followuid'] = $this->userinfo['user_id'];
                    $data['user_id'] = $author_id;
                    $data['is_del'] = 1;
                    $data['create_time'] = time();
                    
                    $this->db->trans_begin();
                    $this->db->insert("bbs_fans",$data);
                    $query1 = $this->db->affected_rows();
                    $query2 = $this->db->query("update tan_bbs_count set fans_count = fans_count + 1 where user_id = ".$author_id);
                    $query3 = $this->db->query("update tan_bbs_count set following_count = following_count + 1 where user_id = ".$this->bbs_userinfo['user_id']);
                    if($query1 && $query2 && $query3){
                        $this->db->trans_commit();
                        
                        
                        //发送消息通知
                        $this->insert_notice(array("user_id"=>$this->userinfo['user_id'],"recieve_id"=>$author_id,"operator_id"=>0,"event_type"=>"event_focus_author","is_show"=>1,"type"=>"system"));
                        //更新个人动态
                        //$this->insert_behavior(array("user_id"=>$this->bbs_userinfo['user_id'],"operator_id"=>$author_id,"event_type"=>"event_focus_author","is_show"=>1,"type"=>"system"));
                        
                        $mess['reqStatus'] = true;
                        echo JSON($mess);exit;
                    }else{
                        $this->db->trans_rollback();
                        $mess['reqStatus'] = false;
                        $mess['errorMsg'] = "操作失败，请稍后重试";
                        echo JSON($mess);exit;
                    }
                    
                    
                }
                
            }else{//删除
                
                $status = $this->db->select("f.*")->from("bbs_fans f")->where(array("f.followuid"=>$this->userinfo['user_id'],"f.user_id"=>$author_id))->order_by("f.create_time desc")->get()->row_array();
                if(!$status){
                    $mess['reqStatus'] = false;
                    $mess['errorCode'] = 1001;
                    $mess['errorMsg'] = "非法操作";
                    echo JSON($mess);exit;
                }
                $this->db->trans_begin();
                $query1 = $this->db->query("update tan_bbs_fans set is_del = 0 where id = ".$status['id']);
                $query2 = $this->db->query("update tan_bbs_count set following_count = following_count - 1 where user_id = ".$this->userinfo['user_id']);
                $query3 = $this->db->query("update tan_bbs_count set fans_count = fans_count - 1 where user_id = ".$author_id);
                
                if($query1 && $query2 && $query3){
                    $this->db->trans_commit();
                    $mess['reqStatus'] = true;
                    echo JSON($mess);exit;
                }else{
                    $this->db->trans_rollback();
                    $mess['reqStatus'] = false;
                    $mess['errorMsg'] = "操作失败，请稍后重试";
                    echo JSON($mess);exit;
                }
                
            }
        }
    }
    //举报
    function ajax_report(){
        $this->is_login();
        if($_POST){
            $type = isset($_POST['type']) ? trim($_POST['type']) : "其他";
            $content = isset($_POST['des']) ? trim($_POST['des']) : "";
            $rel = isset($_POST['rel']) ? trim($_POST['rel']) : "";
            
            $data = array();
            $data['target_type'] = $type;
            $data['target_content'] = $content;
            $data['target_rel'] = $rel;
            $data['create_time'] = time();
            $this->db->insert("bbs_report_list",$data);
            
            $mess['reqStatus'] = true;
            $mess['errorMsg'] = "举报成功！";
            echo JSON($mess);exit;
            
        }
    }
    
    //兑换溜珠
    function ajax_exchange(){
        if($_POST){
            $this->is_login();
            $exchangeNum = isset($_POST['exchangeNum']) ? trim($_POST['exchangeNum']) : 0;
            $exchangePass = isset($_POST['exchangePass']) ? trim($_POST['exchangePass']) : 0;
            if(!$exchangeNum){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "请输入有效的兑换个数";
                echo JSON($mess);exit;
            }
            if($exchangeNum < 10){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "兑换个数需≥10";
                echo JSON($mess);exit;
            }
            
            if(($exchangeNum * 10000) > $this->user_info['balance']){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "余额不足，无法兑换哦";
                echo JSON($mess);exit;
            }
            
            if(!$exchangePass){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "交易密码有误";
                echo JSON($mess);exit;
            }
            if($this->user_info['paypassword'] != md5(md5($exchangePass) .$this->user_info['salt'])){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "请输入正确的交易密码";
                echo JSON($mess);exit;
            }
            
            $this->db->trans_begin();//开启事务
            $account_data = array();
            $account_data['balance'] = $this->user_info['balance'] - ($exchangeNum * 10000);
            $account_data['expend'] = $this->user_info['expend'] + ($exchangeNum * 10000);
            $query1 = $this->db->where("user_id",$this->user_info['user_id'])->update("account",$account_data);
            
            $bbs_account_data = array();
            $bbs_account_data['balance'] = $this->user_info['bbs_account']['balance'] + $exchangeNum;
            $bbs_account_data['total'] = $this->user_info['bbs_account']['total'] + $exchangeNum;
            $query2 = $this->db->where("user_id",$this->user_info['user_id'])->update("bbs_account",$bbs_account_data);
            if($query1 && $query2){
                $this->db->trans_commit();//提交事务
                //溜溜币明细
                $finance_list_data = array();
                $finance_list_data['user_id'] = $this->userinfo['user_id'];
                $finance_list_data['content'] = "兑换".$exchangeNum."个溜珠";
                $finance_list_data['finance'] = ($exchangeNum * 10000);
                $finance_list_data['finance_balance'] = $account_data['balance'];
                $finance_list_data['reward_type'] = 'exchange_deduct';
                $finance_list_data['type'] = 2;//支出
                $finance_list_data['create_time'] = time();
                $finance_list_data['month'] = date("Ym");
                $finance_list_data['day'] = date("Ymd");
                $this->db->insert("finance_list",$finance_list_data);
                
                //溜珠明细
                $zhu_detail = array();
                $zhu_detail['user_id'] = $this->userinfo['user_id'];
                $zhu_detail['num'] = $exchangeNum;
                $zhu_detail['type'] = "溜溜币兑换";
                $zhu_detail['style'] = 1;
                $zhu_detail['create_time'] = time();
                $this->db->insert("bbs_zhu_detail",$zhu_detail);
                
                $log_data = array();
                $log_data['user_id'] = $this->userinfo['user_id'];
                $log_data['events'] = 'exchange';
                $log_data['content'] = '成功兑换'.$exchangeNum."个溜珠，消耗".($exchangeNum * 10000)."个溜溜币";
                $log_data['ip'] = $this->input->ip_address();
                $log_data['create_time'] = time();
                $this->db->insert("users_log",$log_data);
                
                $mess['reqStatus'] = true;
                $mess['errorMsg'] = "成功兑换，溜珠余额：".$bbs_account_data['balance'];
                echo JSON($mess);exit;
                
            }else{
                $this->db->trans_rollback();//事务回滚
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "操作失败，请稍后重试";
                echo JSON($mess);exit;
            }
        }
    }
    //筛选页-平台列表
    function get_plat_json(){
        if($_POST){
            $pageIndex = isset($_POST['pageIndex']) ? trim($_POST['pageIndex']) : 0;
            $type = isset($_POST['types']) ? trim($_POST['types']) : "";
            $type = explode(",", $type);
            $where = array();
            $type[0] ? $where['i.bg_type'] = $type[0] : $where['i.bg_type !='] = 73;
            $type[1] ? $where['i.income_type'] = $type[1] : "";
            $type[2] ? $where['i.interest_type'] = $type[2] : "";
            $type[3] ? $where['i.province_type'] = $type[3] : "";
            $type[4] ? $where['i.online_type'] = $type[4] : "";
            $type[5] ? $where['i.zczj_type'] = $type[5] : "";
            $type[6] ? $where['i.business_type'] = $type[6] : "";
            $type[7] ? $where['i.zjtg_type'] = $type[7] : "";
            $where['p.is_show'] = 1;
            $records_per_page = 15;
            
            $totalCount = $this->db->select("*")->from("plat_info i")->join("plat p","p.name_en = i.plat_en","left")->where($where)->order_by("p.sort desc,i.id desc")->group_by('i.plat_en')->get()->num_rows();
            $list = $this->db->select("i.plat_en,i.plat_ch,i.bg_type,i.plat_ywlx_str,i.plat_bg_str,i.qiyexinxi,p.plat_interest_desc,p.logo_detail")->from("plat_info i")->join("plat p","p.name_en = i.plat_en","left")->where($where)->order_by("p.sort desc,i.id desc")->group_by('i.plat_en')->limit($records_per_page,$pageIndex*$records_per_page)->get()->result_array();
            $html = "";
            foreach($list as $val){
                $detail_url = site_url("mplat_".$val['plat_en']);
                $qiyexinxi = unserialize($val['qiyexinxi']);
                $plat_category = $this->db->query("select title from tan_plat_category where id = $val[bg_type] order by id desc limit 1")->row_array();
                $html .= "<li>
                                <a class='go-detail f-cb' href='$detail_url' target='_blank'>
                                    <div class='fl series'>$plat_category[title]</div>
                                    <div class='fl c-logo'>
                                        <i><em><img src='$val[logo_detail]' alt='$val[plat_ch]' title='$val[plat_ch]'/></em></i>
                                    </div>
                                    <div class='fl c-brief'>
                                        <i>
                                            <p><b></b><span class='brief-name'>$val[plat_bg_str]</span></p>
                                            <p>平台年化利息：<span class='brief-interest'>$val[plat_interest_desc]</span></p>
                                            <p>注册资本：$qiyexinxi[reg_capital]</p>
                                            <p>业务类型：$val[plat_ywlx_str]</p>
                                        </i>
                                    </div>
                                </a>
                            </li>";
            }
            $result = array(
                "reqStatus" => true,
                "data" => array(
                    "totalCount" => $totalCount ? $totalCount : 0,
                    "pageIndex" => $pageIndex,
                    "htmlData" => $html
                )
            );
            echo json_encode($result,JSON_HEX_TAG);die;
            
        }
    }
    //关键词搜索平台
    function get_plat_seach(){
        if($_POST){
            $key_str = isset($_POST['keyStr']) ? trim($_POST['keyStr']) : "";
            $str_en = preg_replace('/([\x80-\xff]*)/i','',$key_str);//将中文去掉
            $str_ch = preg_replace('/[0-9a-zA-Z]+/','',$key_str);//将字母去掉
            $where = "1=1 and p.is_show = 1";
            if($str_en && $str_ch){
                $where .= " and (i.plat_ch like '%$str_ch%' or i.short_name like '%$str_en%' or i.full_name like '%$str_en%')";
            }elseif($str_en){
                $where .= " and (i.short_name like '%$str_en%' or i.full_name like '%$str_en%')";
            }elseif($str_ch){
                $where .= " and i.plat_ch like '%$str_ch%'";
            }
            $list = $this->db->query("select i.short_name,i.plat_ch,i.plat_en from tan_plat_info i left join tan_plat p on p.name_en = i.plat_en where $where order by i.id desc")->result_array();
            $html = "";
            foreach ($list as $val){
                $html .= "<a href='".site_url("mplat_".$val['plat_en'])."' target='_blank'>$val[short_name]($val[plat_ch])</a>";
            }
            $result = array(
                "reqStatus" => true,
                "seachRes" => $html
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
    }
    //判断是否登录
    private function is_login(){
        if($_POST && !$this->userinfo){
            $mess['reqStatus'] = false;
            $mess['errorCode'] = 1001;
            $mess['errorMsg'] = "请先登录，再操作哦";
            echo JSON($mess);exit;
        }
        if($_GET && !$this->userinfo){
           redirect("/");
        }
    }
}
